'use client';

import useToast from '@/hooks/useToast';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { useQuery } from '@tanstack/react-query';
import { search } from '@/services/api';
import type { IPagination, IPost, IQueryParams } from '@/interfaces';
import { type ChangeEvent, useState } from 'react';
import Link from 'next/link';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import type { ISearchPageContext } from '@/contexts/search';
import Pagination from '@/app/[locale]/admin/common/pagination';

export default function SearchPage({
  source,
  translatedFields,
}: ISearchPageContext) {
  const { show } = useToast();
  const [name, setName] = useState(source.queryParams.v ?? '');
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
  });

  const searchQuery = useQuery(
    ['/search', name, params],
    async (context) => {
      return (await search({
        query: {
          ...(context.queryKey[2] as any),
          name: encodeURIComponent(context.queryKey[1] + ''),
        },
      })) as IPagination<IPost>;
    },
    {
      enabled: !!(name && name.length > 1),
      keepPreviousData: true,
    },
  );

  function onClickPrevious() {
    const data = searchQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: translatedFields.dataNotExists,
      });
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = searchQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: translatedFields.dataNotExists,
      });
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  function onChangeName(e: ChangeEvent<HTMLInputElement>) {
    setName(e.target.value);
  }

  return (
    <div className="col px-2 py-4">
      <div className="card border-0">
        <div className="card-body vh-100 overflow-y-auto container vstack gap-4 py-4">
          <input
            name="name"
            value={name}
            onChange={onChangeName}
            className="form-control"
            type="search"
            placeholder={translatedFields.pleaseEnterSearchContent}
            aria-label="name"
          />

          {searchQuery.data && (
            <div className="vstack gap-4">
              {searchQuery.data.content.length > 0 && (
                <div className="card">
                  <div className="card-header user-select-none">
                    {translatedFields.relatedData}
                  </div>
                  <div className="list-group list-group-flush">
                    {searchQuery.data.content.map((item) => {
                      return (
                        <Link
                          key={item.id}
                          href={`/posts/${item.id}`}
                          className="list-group-item list-group-item-action"
                          target="_blank"
                        >
                          {item.name}
                        </Link>
                      );
                    })}
                  </div>
                </div>
              )}

              {searchQuery.data.content.length === 0 && <Nodata />}

              <Pagination
                isShow={searchQuery.data.pageable.pages > 0}
                onPrevious={onClickPrevious}
                onNext={onClickNext}
                isPrevious={searchQuery.data.pageable.previous}
                isNext={searchQuery.data.pageable.next}
                translatedFields={{
                  previous: translatedFields.previousPage,
                  next: translatedFields.nextPage,
                }}
              />
            </div>
          )}

          {searchQuery.isError && (
            <Alert message={searchQuery.error} type="error" />
          )}

          {name && name.length > 1 && searchQuery.isLoading && <AlertLoad />}
        </div>
      </div>
    </div>
  );
}
